package cn.edu.sdu.sol.intake_system.service;

import cn.edu.sdu.sol.intake_system.model.po.*;
import cn.edu.sdu.sol.intake_system.model.vo.DataRequest;
import cn.edu.sdu.sol.intake_system.model.vo.DataResponse;
import cn.edu.sdu.sol.intake_system.repository.*;
import cn.edu.sdu.sol.intake_system.utils.JwtUtil;
import cn.edu.sdu.sol.intake_system.utils.PersonInfUtils;
import cn.edu.sdu.sol.intake_system.utils.VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class QuestionService {
    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    UserRepository userRepository;

    @Autowired
    DepartmentRepository departmentRepository;

    VO vo = new VO();

    @Autowired
    PersonInfUtils personInfUtils;
    @Autowired
    private QuestionRepository questionRepository;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private StationRepository stationRepository;
    @Autowired
    private WillRepository willRepository;
    @Autowired
    private ScoreRepository scoreRepository;
    @Autowired
    private AnswerRepository answerRepository;

    public DataResponse questionEdit(DataRequest req, String token) {
        // 获取用户信息
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        assert sysUser.isPresent();
        // Integer departmentQuestionId = req.getInteger("departmentQuestionId");
        // String stem = req.getString("stem");
        // Integer departmentId = req.getInteger("departmentId");
        Integer departmentId = sysUser.get().getAdminInf().getDepartment().getDepartmentId();
        Department department = departmentRepository.findDepartmentByDepartmentId(departmentId).get();


        List<Question> questions = questionRepository.findQuestionListByDepartmentId(departmentId);
        for (Question question : questions) {
            List<Answer> answers = answerRepository.findByQuestionQuestionId(question.getQuestionId());
            answerRepository.deleteAll(answers);
        }
        questionRepository.deleteAll(questions);

        List<Map<String, Object>> questionS = req.getList("questions");

        for(Map<String, Object> questionMap: questionS){
            Integer departmentQuestionId = (Integer) questionMap.get("departmentQuestionId");
            String stem = (String) questionMap.get("stem");
//            Optional<Question> q0 = questionRepository.findQuestionByDepartmentQuestionIdAndDepartmentId(departmentQuestionId,departmentId);
            Question q = new Question();
            q.setDepartmentQuestionId(departmentQuestionId);
            q.setDepartment(department);
            q.setStem(stem);
            questionRepository.saveAndFlush(q);
        }
        return new DataResponse(200, null, "修改成功~");
    }

    public DataResponse getQuestion(DataRequest req, String token) {
        Integer departmentId = req.getInteger("departmentId");
        List dataList = getQuestionListByDepartmentId(departmentId);
        return new DataResponse(200, dataList, "ok");
    }

    private Object getMapFromQuestion(Question question) {
        Map m = new HashMap();
        if (question == null) {
            return m;
        }
        m.put("questionId", question.getQuestionId());
        m.put("stem", question.getStem());
        m.put("departmentQuestionId",question.getDepartmentQuestionId());
        return m;
    }

    public List getQuestionListByDepartmentId(Integer departmentId) {
        Department d = departmentRepository.findDepartmentByDepartmentId(departmentId).get();
        List dataList = new ArrayList();
        List<Question> qList = questionRepository.findQuestionListByDepartmentId(departmentId);
        if (qList == null || qList.size() == 0) {
            return dataList;
        }
        for (int i = 0; i < qList.size(); i++) {
            dataList.add(getMapFromQuestion(qList.get(i)));
        }
        return dataList;
    }

    public DataResponse getQuestionByOrder(DataRequest req, String token) {
        //获取用户信息
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        if  (sysUser.isEmpty()) {
            return vo.messageError("用户不存在!");
        }
        SysUser s = sysUser.get();
        PersonInf p = s.getPersonInf();
        Integer personId = s.getPersonInf().getPersonInfPk();
        Integer willOrder = req.getInteger("willOrder");
        Optional<Will> will = willRepository.findWillListByPersonInfPkAndWillOrder(personId, willOrder);
        Will w = new Will();
        if (will.isPresent()) {
            w = will.get();
            Integer departmentId = w.getDepartment().getDepartmentId();
            List dataList = getQuestionListByDepartmentId(departmentId);
            return new DataResponse(200,dataList,"ok");
        } else {
            return vo.messageError("不存在");
        }
  
    }

    public DataResponse submitAnswers(DataRequest req, String token) {
        //获取用户信息
        token = jwtUtil.extractTokenFromHeader(token);
        String studentNum = jwtUtil.getStudentNumFromToken(token);
        Optional<SysUser> sysUser = userRepository.findUserByStudentNum(studentNum);
        if  (sysUser.isEmpty()) {
            return vo.messageError("用户不存在!");
        }
        SysUser s = sysUser.get();
        PersonInf p = s.getPersonInf();
        Integer personId = s.getPersonInf().getPersonInfPk();
        List<Map<String, Object>> answers = req.getList("answers");
        for (Map<String, Object> answer : answers) {
            Answer a = new Answer();
            Integer questionId = (Integer) answer.get("questionId");
            String answerText = (String) answer.get("answer");
            Optional<Question> question = questionRepository.findQuestionByQuestionId(questionId);
            if (question.isEmpty()) {
                return vo.messageError("不存在该问题");
            }
            Optional<Answer> answer0 = answerRepository.findAnswerByPersonIdAAndQuestionId(personId, questionId);
            if (answer0.isPresent()) {
                a = answer0.get();
            }
            Question q = question.get();
            a.setAnswer(answerText);
            a.setQuestion(q);
            a.setPerson(p);
            answerRepository.saveAndFlush(a);
        }
        return new DataResponse(200, null, "ok");
    }
}


